package com.lx.util.secure.algorithm.summary;


import com.lx.annotation.Note;
import com.lx.util.secure.algorithm.SummaryAlgorithm;
import com.lx.util.secure.algorithm.coder.CoderType;
import com.lx.util.secure.algorithm.coder.Hex;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

public class Sha extends SummaryAlgorithm<Sha> {

    private static final Sha sha = new Sha();
    public static Sha getInstance() {
        return sha;
    }

    @Override
    protected CoderType defaultCoderType() {
        return CoderType.HEX;
    }

    @Override
    protected String defaultEncryptAlgorithm() {
        return "SHA-256";
    }

    @Override
    public byte[] encrypt(byte[] bytes) {
        return digest(getEncryptAlgorithm(),bytes);
    }

    @Override
    protected CoderType defaultKeyCoderType() {
        return null;
    }

    @Note("sha256哈希算法")
    public static String sha256(String data){
        return Hex.getCoder().encodeToString(digest("SHA-256",data.getBytes(StandardCharsets.UTF_8)));
    }

    public static String sha256(byte[] data){
        return Hex.getCoder().encodeToString(digest("SHA-256",data));
    }

    public static byte[] digest(String algorithm, byte[] bytes) {
        try {
            MessageDigest md = MessageDigest.getInstance(algorithm);
            return md.digest(bytes);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}